from decimal import Decimal
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU
from orders.serializers import OrdersPlacesSerializer, PlacesOrdersSerializer, OrderSerializer

'''
请求方式 ： GET /orders/places/
从购物车页面跳转而来的
需要返回的数据　运费　商品id 商品图片　数量　商品的单价　结算商品列表　商品单价
'''
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection


class OrdersPlacesAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request):
        user = request.user
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s'%user.id)
        redis_selected = redis_conn.smembers('cart_selected_%s'%user.id)

        cart = {}
        for sku_id,count in redis_cart.items():
            cart[int(sku_id)] = int(count)
        skus = SKU.objects.filter(pk__in = redis_selected)

        for sku in skus:
            sku.count = cart[sku.id]
        # 存储的是字符串１０
        freight = Decimal('10')

        # serializer = OrdersPlacesSerializer(skus,many=True)
        serializer = PlacesOrdersSerializer({
            'freight': freight,
            'skus': skus
        })

        return Response(serializer.data)


class OrderAPIView(APIView):

    def post(self,request):

        data = request.data

        serializer = OrderSerializer(data = data,context={'request':request})
        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.data)
